package com.wiki.gds.user.provider.modular.sys.controller;


import com.wiki.gds.base.common.dto.ResponseDto;
import com.wiki.gds.base.common.exception.BizExceptionEnum;
import com.wiki.gds.base.security.admin.utils.SecurityUtil;
import com.wiki.gds.base.security.common.model.SecurityUser;
import com.wiki.gds.base.web.controller.common.BaseController;
import com.wiki.gds.base.web.controller.support.HttpKit;
import com.wiki.gds.user.facade.sys.model.User;
import com.wiki.gds.user.facade.sys.model.query.UserQuery;
import com.wiki.gds.user.provider.modular.sys.service.DeptService;
import com.wiki.gds.user.provider.modular.sys.service.UserService;
import io.swagger.annotations.*;
import org.hibernate.validator.constraints.Length;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.List;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

@Api(value = "UserController", tags = "用户中心微服务-用户管理")
@RestController
@RequestMapping("user")
@Validated
public class UserController extends BaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private DeptService deptService;

    @PostMapping
    @ApiOperation(value = "修改用户密码", notes = "修改用户密码", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "请输入凭证", required = true, dataType = "String", paramType = "header"),
            @ApiImplicitParam(name = "newPwd", value = "新密码", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "oldPwd", value = "旧密码", required = true, dataType = "String", paramType = "query")
    })
    public ResponseDto modifyPwd(
            @NotEmpty(message = "新密码不能为空")
                    String newPwd,
            @NotEmpty(message = "旧密码不能为空") @Length(min = 6, message = "密码长度不能小于6位")
                    String oldPwd
    ) {
        ResponseDto rs = new ResponseDto(BizExceptionEnum.SUCCESSFUL_OPERATION);
        SecurityUser securityUser = SecurityUtil.getSecurityUser();
        oldPwd = DigestUtils.md5DigestAsHex(oldPwd.getBytes());
        if (!oldPwd.equals(securityUser.getPassword())) {
            return new ResponseDto(BizExceptionEnum.LOGIN_PASSWORD_ERROR);
        }
        User user = new User();
        user.setId(securityUser.getId());
        user.setPassword(DigestUtils.md5DigestAsHex(newPwd.getBytes()));
        if (!userService.update(user)) {
            rs.ChangeBizException(BizExceptionEnum.FAIL_OPERATION);
        }
        return rs;
    }
    @ApiOperation(value = "图片验证码注册", notes = "图片验证码注册", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "imgCode", value = "图片验证码", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "user", value = "请输入用户信息", required = true, dataType = "UcUser", paramType = "body")
})
    @PostMapping
    public ResponseDto register(@Validated  @RequestBody User user,@Validated String imgCode) {
        ResponseDto rs = new ResponseDto(BizExceptionEnum.SUCCESSFUL_OPERATION);
         String sessionImgCode= (String) HttpKit.getRequest().getSession().getAttribute(KAPTCHA_SESSION_KEY);
         if(sessionImgCode==null){
             return new ResponseDto(BizExceptionEnum.V_CODE_NULL);
         }
         if(!sessionImgCode.equals(imgCode)){
             return new ResponseDto(BizExceptionEnum.V_CODE_ERROR);
         }
         user.setStatus(1);
         user.setUsertype(0);
        Long aa= userService.insert(user);
        System.out.println(aa);
        return rs;
    }

    @PostMapping("auth_user")
    @ApiOperation(value = "用户授权角色", notes = "用户授权角色", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "请输入凭证", required = true, dataType = "String", paramType = "header"),
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "rids", value = "角色id字符串", required = true, dataType = "String", paramType = "query"),

    })
    public ResponseDto authUser(@NotNull(message = "用户id不能为空") Long userId, @NotNull(message = "角色id字符串不能为空") String rids){
        ResponseDto rs=new ResponseDto(BizExceptionEnum.SUCCESSFUL_OPERATION);
        User user=userService.getById(userId);
        if(user==null){
            rs.ChangeBizException(BizExceptionEnum.NO_THIS_USER);
            return rs;
        }
        userService.authUser(userId,rids);
        return rs;
    }

    @PostMapping("list")
    @ApiOperation(value = "用户列表", notes = "用户列表", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "请输入凭证", required = true, dataType = "String", paramType = "header"),
            @ApiImplicitParam(name = "userQuery", value = "请输入用户查询信息", required = true, dataType = "UserQuery", paramType = "body") })
    @ApiResponses(
            @ApiResponse(code = 200,response = User.class,message = "data：中返回list")
    )
    public ResponseDto userList(@Validated @RequestBody UserQuery userQuery) throws Exception {
        ResponseDto rs=new ResponseDto(BizExceptionEnum.SUCCESSFUL_OPERATION);
        Long deptId=SecurityUtil.getSecurityUser().getDeptId();
        if(userQuery.getDeptId()==null){
            userQuery.setDeptId(deptId);
        }else {
            if(deptId!=0){
                List<Long> list=deptService.deptIdsByPid(deptId);
                if(!list.contains(userQuery.getDeptId())){
                    rs.setCode(BizExceptionEnum.FAIL_OPERATION.getCode());
                    rs.setMesg("查看部门权限不足");
                    return  rs;
                }
            }
        }
        rs.setData(userService.listByDept(userQuery));
        return rs;
    }

    @PostMapping("save")
    @ApiOperation(value = "用户添加或修改", notes = "用户添加或修改", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "请输入凭证", required = true, dataType = "String", paramType = "header"),
            @ApiImplicitParam(name = "user", value = "请输入角色信息", required = true, dataType = "User", paramType = "body") })
    public ResponseDto saveOrUpdate(@RequestBody @Validated User user){
        ResponseDto rs=new ResponseDto(BizExceptionEnum.SUCCESSFUL_OPERATION);
        User checkUser=new User();
        checkUser.setLoginname(user.getLoginname());
        checkUser= userService.getBySelf(checkUser);
        if(checkUser!=null){
          rs.ChangeBizException(BizExceptionEnum.USER_ALREADY_REG);
          return rs;
        }
        userService.saveOrUpdate(user);
        return rs;
    }

    @PostMapping("del")
    @ApiOperation(value = "删除用户", notes = "删除用户", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "请输入凭证", required = true, dataType = "String", paramType = "header"),
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "Long", paramType = "query")})
    public ResponseDto del(@NotNull(message = "用户id不能为空") String  userIds){
        ResponseDto rs=new ResponseDto(BizExceptionEnum.SUCCESSFUL_OPERATION);
        userService.delBatch(userIds);
        return rs;
    }


    @PostMapping("change_status")
    @ApiOperation(value = "修改账号停用启用", notes = "修改账号停用启用", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "请输入凭证", required = true, dataType = "String", paramType = "header"),
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "Long", paramType = "query")})
    public ResponseDto changeStatus(@NotNull(message = "用户id不能为空") String  userIds,Integer type){
        ResponseDto rs=new ResponseDto(BizExceptionEnum.SUCCESSFUL_OPERATION);
        userService.changeStatus(userIds,type);
        return rs;
    }

}
